from django.http import HttpResponse
from urllib2 import urlopen
from simplejson import loads
from django.http import HttpResponseRedirect
import uuid
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response

@csrf_exempt
def index(request):
#    content = loads(urlopen('https://graph.facebook.com/me?access_token=AAAD5XLJwU8UBAGZABZBITEfZC42tnRXhbZBsB6kFIxeQH7koEtZBWB3dnGuYsyAlwW9zSqMyZBhStmD8BwZApzf8a68QYJ0BkjjZCgPLgfXhEgZDZD').read())
#   return HttpResponse(content.__str__())
    if "ACCESS_TOKEN" not in request.session or request.session["ACCESS_TOKEN"] == None:
        return HttpResponseRedirect("https://www.facebook.com/dialog/oauth?client_id=274176526013381"+
                                    "&redirect_uri=https://apps.facebook.com/alagenchev/authentication/new_token/&state=" + uuid.uuid4().__str__()+"&scope=user_photos")
    else:
        return HttpResponse("<script type='text/javascript'>top.location.href = 'https://apps.facebook.com/alagenchev/authentication/result/';</script>")
# Initialize the Graph API with a valid access token (optional,
# but will allow you to do all sorts of fun stuff).
#graph = GraphAPI(oauth_access_token)

# Get my latest posts
#graph.get('me/posts')


    #return HttpResponse("Hello, world. You're at the poll index.")
    
@csrf_exempt
def new_token(request):
    code = request.GET.get("code")
    url = "https://graph.facebook.com/oauth/access_token?client_id=274176526013381&redirect_uri=https://apps.facebook.com/alagenchev/authentication/new_token/&client_secret=575d39623115bb472f4632908f323f26&code=" + code;
    
    content = urlopen(url).read()
    
    token = content.split('=')
    
    access_token = token[1].split('&')[0]
    request.session["ACCESS_TOKEN"] = access_token
    
    return HttpResponse("<script type='text/javascript'>top.location.href = 'https://apps.facebook.com/alagenchev/authentication/result/';</script>")

@csrf_exempt
def result(request):
    #albums.
    #result = 
    url  = 'https://graph.facebook.com/me?access_token=' + request.session["ACCESS_TOKEN"]
    content = loads(urlopen(url).read())
    
#    return HttpResponse("id is " + content["id"].__str__())
#    
#    for key,value in content.iteritems():
#        print "key: "+ key.__str__() + " value: " + value.__str__()
#           
#    url  = 'https://graph.facebook.com/me/albums?access_token=' + request.session["ACCESS_TOKEN"]
#    content = loads(urlopen(url).read())
#    
#    i = 0
#    for key,value in content.iteritems():
#        if i!=0:
#            for val in value:
#                print val["name"].__str__()
#        i +=1
    return render_to_response('user/index.html', {'userId' : content["id"]})




